import { startsWith } from 'lodash'
import { get } from './request'
import { parseList, v2 as _v2 } from './common'

function parseChapter (source: any, doc: string) {
  if (source.ruleSearch) {
    return v3.parseChapter(source, doc)
  } else {
    return v2.parseChapter(source, doc)
  }
}

async function downloadChapter (source: any, url: string) {
  if (source.ruleSearch) {
    return v3.downloadChapter(source, url)
  } else {
    return v2.downloadChapter(source, url)
  }
}

const v3 = {
  parseChapter (source: any, doc: string) {
    const { chapterList, ...restRules } = source.ruleToc

    return parseList(doc, chapterList, restRules)
  },

  async  downloadChapter (source: any, url: string) {
    if (!startsWith(url, 'http')) {
      url = source.bookSourceUrl + url
    }
    return get(url)
  }
}

const v2 = {
  parseChapter (source: any, doc: string) {
    // const $ = cheerio.load(doc)

    // const list = parseRule(source.ruleChapterList, $)

    const chapterMap = {
      chapterName: source.ruleChapterName,
      chapterUrl: source.ruleContentUrl
      // ruleBookContent: 'ruleBookContent'
    }

    // const chapterItems = []

    // list.each(function () {
    //   const item = {}
    //   Object.keys(chapterMap).forEach(prop => {
    //     item[prop] = _.trim(parseRule(source[chapterMap[prop]], $(this)))
    //   })
    //   if (item.chapterName) {
    //     chapterItems.push(item)
    //   }
    // })
    // return chapterItems

    return parseList(doc, source.ruleChapterList, chapterMap)
  },

  async  downloadChapter (source: any, url: string) {
    if (!startsWith(url, 'http')) {
      url = source.bookSourceUrl + url
    }
    const { options } = _v2.parseSearchUrl(source)
    return get(url, options)
  }
}

export {
  parseChapter,
  downloadChapter
}
